from pyecharts.charts import Bar, Pie, Page
from pyecharts import options as opts
import pandas as pd
from pyecharts.globals import ThemeType
from bs4 import BeautifulSoup
import numpy as np
import jieba
from snownlp import SnowNLP
from pyecharts.charts import WordCloud, Funnel
from pyecharts.charts import Map
from datetime import datetime
from flask import Flask
from flask import render_template

data = pd.read_excel(r'../data/新型冠状病毒肺炎疫情地图.xlsx')
data1 = [list(z) for z in zip(data["省市地区"].to_list(), data["新增确诊"].to_list())]

data_xz = data.loc[data['新增确诊'] == 0, :]
data_xz1 = [list(z) for z in zip(data_xz["省市地区"].to_list(), data_xz["新增确诊"].to_list())]

map1 = (
    Map(init_opts=opts.InitOpts(width="700px", height="700px", theme=ThemeType.LIGHT))
        .add("", data1, "china")
        .set_series_opts(showLegendSymbol=False)
        .add("", data_xz1, "china", itemstyle_opts=opts.ItemStyleOpts(color="red", ), )
        .set_global_opts(
        title_opts=opts.TitleOpts(
            title="各省市新增确诊分布情况",
            pos_top='20%', pos_left='35%',
            title_textstyle_opts=opts.TextStyleOpts(color='#CCFFFF', )),
        visualmap_opts=opts.VisualMapOpts(is_piecewise=False, pos_top='82%', pos_left='30%',
                                          orient="horizontal",
                                          range_text=['以上', ' '],
                                          range_color=['#FFFFFF', '#0099CC'],
                                          max_=200,
                                          item_width=30,
                                          item_height=300,
                                          ),
    )
)
# map1.render("../TestHTML/map.html")
data_xz = data.loc[data['新增无症状'] != 0, :]
a = data_xz["省市地区"].to_list()
b = data_xz["新增无症状"].to_list()
# print([list(z) for z in zip(a, b)])

funnel = (
    Funnel(init_opts=opts.InitOpts(theme=ThemeType.LIGHT,
                                   width="700px",
                                   height="700px",
                                   ))
        .add(
        "无症状病例数",
        [list(z) for z in zip(a, b)],
        sort_="descending",  # 数据排序:下降
        label_opts=opts.LabelOpts(position="inside"),

    )
        .set_global_opts(
        title_opts=opts.TitleOpts(
            title="新增无症状数量情况",
            pos_top='10px',
            pos_left='40%',
            title_textstyle_opts=opts.TextStyleOpts(color='#CCFFFF', )),
        legend_opts=opts.LegendOpts(
            pos_top='35%',
            pos_left='10%',
            orient='vertical',  # 布局朝向:垂直

        ),

    )

)
# funnel.render("../testHTML/funnel_label_inside.html")


remark_data = pd.read_excel(r'../data/评论.xlsx')

remark_data['词性标注'] = remark_data['评论'].agg(lambda x: list(SnowNLP(x).tags))

list_tags = []
for i in remark_data['词性标注']:
    for j in i:
        list_tags.append(j)

data_tags = pd.DataFrame(list_tags, columns=['词语', '词性'])
data_tags['词性'].value_counts()
result = data_tags[data_tags['词性'] == 'a'].groupby(by='词语')['词语'].count().sort_values(ascending=False)  # [:20]
data_wordcloud_tags = [(i, str(j)) for i, j in zip(result.index, result.values)]

word = (
    WordCloud(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="400px",
                                      height="400px", ))
        .add(series_name="",
             data_pair=data_wordcloud_tags,
             word_size_range=[20, 70],
             #          mask_image="./口罩.jpg",

             textstyle_opts=opts.TextStyleOpts(font_family="cursive"),  # 文字的字体系列
             shape='cardioid',  # 词云图轮廓:心形
             )
        .set_global_opts(
        title_opts=opts.TitleOpts(
            title="近期关于疫情的评论热词",
            pos_top='16%',
            #             pos_left='10%'
            title_textstyle_opts=opts.TextStyleOpts(color='#CCFFFF', )

        ),
        tooltip_opts=opts.TooltipOpts(is_show=True),

    )
)
# word.render("../TestHTML/word.html")


domestic_data = [50797, 3450756, 18787, 295456]
foreign_data = [307317, 536147056, 6312555, 512815298]
title = ['新增确诊', '累计确诊', '累计死亡', '累计治愈']

bar = (
    Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="700px", height="700px",
                                animation_opts=opts.AnimationOpts(animation_delay=1000,
                                                                  animation_easing="elasticOut")), )  # 初始动画的缓动效果。
        .add_xaxis(data["省市地区"].to_list())
        .add_yaxis("新增确诊", data["新增确诊"].to_list())
        .add_yaxis("新增无症状", data["新增无症状"].to_list())
        .add_yaxis("累计确诊", data["累计确诊"].to_list())
        .set_global_opts(
        toolbox_opts=opts.ToolboxOpts(orient="horizontal", pos_left='13%', pos_top='5%'),
        title_opts=opts.TitleOpts(title="各省市地区情况", title_textstyle_opts=opts.TextStyleOpts(color='#CCFFFF', )),
        yaxis_opts=opts.AxisOpts(name="病例数", axislabel_opts=opts.LabelOpts(formatter="{value}/例")),
        xaxis_opts=opts.AxisOpts(name="地区"),
        legend_opts=opts.LegendOpts(pos_left='30%'),
        datazoom_opts=opts.DataZoomOpts(orient="horizontal", type_='inside', ),  # 组件类型：里面
    )
        .set_series_opts(
        itemstyle_opts={  # 形成圆柱效果
            "normal": {
                "barBorderRadius": [30, 30, 30, 30],
                "shadowColor": "rgb(0, 160, 221)",
            }
        },
        label_opts=opts.LabelOpts(is_show=False, ),  # 标签配置项

    )
)
# bar.render("../TestHTML/bar.html")

data_xz = data.loc[data['风险地区'] != 0, :]

a_1 = data_xz["省市地区"].to_list()
b_1 = data_xz["风险地区"].to_list()

pie = (
    Pie(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="700px", height="700px", ), )
        .add(
        "", [list(z) for z in zip(a_1, b_1)], radius=["40%", "55%"],  # 饼图的半径
        label_opts=opts.LabelOpts(
            position="outside",  # 标签的位置
            formatter="{a|{a}}{abg|}\n{hr|}\n {b|{b}: }{c}  {per|{d}%}  ",  # 标签内容格式器
            background_color="#eee",  # 文字块背景色
            border_color="#aaa",  # 图形的描边颜色
            border_width=1,  # 描边宽度
            border_radius=4,  # 文字块的圆角
            rich={  # 富文本样式
                "a": {"color": "#999", "lineHeight": 22, "align": "center"},
                "abg": {
                    "backgroundColor": "#e3e3e3",
                    "width": "100%",
                    "align": "right",
                    "height": 22,
                    "borderRadius": [4, 4, 0, 0],
                },
                "hr": {
                    "borderColor": "#aaa",
                    "width": "100%",
                    "borderWidth": 0.5,
                    "height": 0,
                },
                "b": {"fontSize": 16, "lineHeight": 33},
                "per": {
                    "color": "#eee",
                    "backgroundColor": "#334455",
                    "padding": [2, 4],
                    "borderRadius": 2,
                },
            },
        ),
    )
        .set_global_opts(title_opts=opts.TitleOpts(
        title="风险地区数量", pos_top='49%', pos_left='39%',
        title_textstyle_opts=opts.TextStyleOpts(color='#CCFFFF', )),
    )
)
# pie.render("../TestHTML/pie.html")

now_time = datetime.now().strftime('%Y-%m-%d')  # 获取当前时间
big_title = (
    Pie(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))  # 不画图，只显示一个标题，用来构成大屏的标题
        .set_global_opts(
        title_opts=opts.TitleOpts(title="疫情分析可视化大屏",
                                  title_textstyle_opts=opts.TextStyleOpts(font_size=40,
                                                                          color='#CCFFFF',
                                                                          font_style='oblique'
                                                                          ),
                                  #                                   subtitle = f'截至：{now_time}',
                                  #                                   pos_top=0,

                                  )
    )
)
# big_title.render("../TestHTML/big_title.html")

page = Page()
page.add(
    big_title,
    map1,
    word,
    bar,
    funnel,
    pie,
)
# page.render("./templates/page.html")

with open("../Test/templates/page.html", "r+", encoding='utf-8') as html:
    html_bf = BeautifulSoup(html, 'lxml')
    divs = html_bf.select('.chart-container')  # 根据css定位标签，选中图像的父节点标签
    divs[0][
        "style"] = "width:50%;height:50%;position:absolute;top:2%;left:40%;border-style:dashed;border-color:#444444;border-width:0px;"
    divs[1][
        "style"] = "width:50%;height:100%;position:absolute;top:0%;left:25%;border-style:solid;border-color:#444444;border-width:0px;"
    divs[2][
        "style"] = "width:35%;height:60%;position:absolute;top:45%;left:65%;border-style:solid;border-color:#444444;border-width:0px;"
    divs[3][
        "style"] = "width:41%;height:53%;position:absolute;top:50%;left:1%;border-style:solid;border-color:#444444;border-width:0px;"
    divs[4][
        "style"] = "width:35%;height:55%;position:absolute;top:0%;left:68%;border-style:solid;border-color:#444444;border-width:0px;"
    divs[5][
        "style"] = "width:35%;height:50%;position:absolute;top:0%;left:0%;border-style:solid;border-color:#444444;border-width:0px;"
    body = html_bf.find("body")  # 根据标签名称定位到body标签
    #     body["style"] = "background-color:#CCCCCC;" # 修改背景颜色
    body["style"] = "background-color:#44cef6;"  # 修改背景颜色
    #     body["style"] = "background-image: url(./a.jpg);" # 修改背景颜色
    html_new = str(html_bf)  # 将BeautifulSoup对象转换为字符
    html.seek(0, 0)  # 光标移动至
    html.truncate()  # 删除光标后的所有字符内容
    html.write(html_new)  # 将由BeautifulSoup对象转换得到的字符重新写入html文件
    html.close()



# 创建flask对象
app = Flask(__name__)


# 设置路由及其内容
@app.route('/')
def hello():
    return render_template("page.html")  # html文件一定要放在templates文件夹中


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=80)  # 局域网电脑通过访问本机的ip地址即可访问网页
